<template>
  <div class="chart-container">
    <p class="chart-title">气流类别汇总</p>
    <div ref="chartElement" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

// Helper function to mirror the 3-point data into a 5-point array
function mirrorData(originalData) {
  if (!Array.isArray(originalData) || originalData.length !== 3) {
    console.warn("Invalid data format for mirroring. Expected array with 3 elements, received:", originalData);
    return [null, null, null, null, null];
  }
  const data_CCT = originalData[0];
  const data_CCT2 = originalData[1];
  const data_Edge = originalData[2];
  return [data_Edge, data_CCT2, data_CCT, data_CCT2, data_Edge];
}

// Define the fixed mirrored x-axis labels
const mirroredXAxisLabels = ['边缘平均', 'CCT2\n（次中心）', 'CCT\n（中心温度）', 'CCT2\n（次中心）', '边缘平均'];

export default {
  name: "AirflowChart2",
  props: {
    baseCategories: {
      type: Array,
      default: () => []
    },
    currentData: {
      type: Object,
      default: () => ({ yAxisData: [] })
    },
  },
  data() {
    return {
      chartInstance: null,
      options: {
        animation: false,
        toolbox: {
          show: false,
          feature: {
            dataZoom: { yAxisIndex: 'none' },
            dataView: { readOnly: true },
            saveAsImage: {}
          },
          top: '8%',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross', crossStyle: { color: '#ccc', width: 1, type: 'solid' } },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#999',
          borderWidth: 1,
          padding: 8,
          textStyle: { color: '#333' },
          formatter: function (params) {
            let result = params[0].axisValueLabel + '<br/>';
            params.forEach(item => {
              result += item.marker + item.seriesName + ': ' + (item.value !== undefined && item.value !== null ? item.value + ' °C' : 'N/A') + '<br>'
            })
            return result
          },
        },
        grid: [],
        xAxis: [],
        yAxis: [],
        series: [],
        color: ['#0037fc', '#6dbcdc', '#a0c782', '#caa5ce', '#93acc4','#f8d3a3','#f8a3a3','#c8e3e3']
      }
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
    this.updateChart();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chartInstance?.dispose();
  },
  watch: {
    baseCategories: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
    currentData: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
  },
  methods: {
    getLabel(str) {
      const match = str.match(/[0-9A-Z]/);
      return match ? match[0] : null;
    },

    initChart() {
      if (!this.$refs.chartElement) return;
      this.chartInstance = echarts.init(this.$refs.chartElement);
    },

    updateChart() {
      if (!this.chartInstance) return;

      // Prepare all series data
      const allSeries = [];
      const legendData = [];

      // Add current data series
      if (this.currentData?.yAxisData?.length === 3) {
        const mirroredCurrentData = mirrorData(this.currentData.yAxisData);
        allSeries.push({
          name: '当前气流',
          type: 'line',
          data: mirroredCurrentData,
          smooth: true,
          lineStyle: { type: 'solid' },
          itemStyle: { color: this.options.color[0] }
        });
        legendData.push('当前气流');
      }

      // Add base categories
      this.baseCategories.forEach((category, index) => {
        if (category.data?.length === 3) {
          const categoryName = this.getLabel(category.name);
          const mirroredBaseData = mirrorData(category.data);
          allSeries.push({
            name: categoryName,
            type: 'line',
            data: mirroredBaseData,
            smooth: true,
            lineStyle: { type: 'solid' },
            itemStyle: { color: this.options.color[(index + 1) % this.options.color.length] }
          });
          legendData.push(categoryName);
        }
      });

      // Calculate grid and axis positions
      const seriesCount = allSeries.length;
      const gridHeight = seriesCount > 0 ? (90 / seriesCount) : 100;
      const grids = [];
      const xAxes = [];
      const yAxes = [];
      const finalSeries = [];

      // Determine global min and max for y-axis
      let globalMax = -Infinity;

      allSeries.forEach(series => {
        const data = series.data;
        const max = Math.max(...data);
        if (max > globalMax) globalMax = max;
      });
      globalMax = Math.ceil(globalMax / 100) * 100;

      allSeries.forEach((series, index) => {
        const top = index * gridHeight + 5;
        if(index === seriesCount - 1) {
          grids.push({
            left: '3%',
            right: '3%',
            top: `${top}%`,
            height: `${gridHeight + 5}%`,
            containLabel: true
          });
        }else{
          grids.push({
            left: '3%',
            right: '3%',
            top: `${top}%`,
            height: `${gridHeight}%`,
            containLabel: true
          });
        }
        // Only show x-axis for the last chart
        xAxes.push({
          gridIndex: index,
          type: 'category',
          data: mirroredXAxisLabels,
          axisLabel: {
            show: index === seriesCount - 1, // Only show labels on last chart
            rotate: 0,
            interval: 0,
            textStyle: { fontSize: 12, color: '#333' }
          },
          axisLine: {
            show: index === seriesCount - 1,
            lineStyle: { color: '#000', type: 'solid', width: 2 }
          },
          splitLine: { show: false }
        });

        yAxes.push({
          gridIndex: index,
          type: 'value',
          min: 0,
          max: globalMax,
          axisLabel: {
            formatter: '{value} °C',
            show: true
          },
        });

        // Assign each series to its grid
        finalSeries.push({
          ...series,
          xAxisIndex: index,
          yAxisIndex: index
        });
      });


      // Update chart options
      this.chartInstance.setOption({
        grid: grids,
        xAxis: xAxes,
        yAxis: yAxes,
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'cross', crossStyle: {color: '#ccc', width: 1, type: 'solid'}},
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#999',
          borderWidth: 1,
          padding: 8,
          textStyle: {color: '#333'},
          formatter: function (params) {
            // Display the correct label from the mirrored axis
            let result = params[0].axisValueLabel + '<br/>'; // Use axisValueLabel for potentially multi-line labels
            params.forEach(item => {
              result += item.marker + item.seriesName + ': ' + (item.value !== undefined && item.value !== null ? item.value + ' °C' : 'N/A') + '<br>'
            })
            return result
          },
        },
        legend: {
          type: 'scroll',
          data: legendData,
          top: '1%',
          textStyle: { fontSize: 12 },
          width: '100%',
        },
        series: finalSeries
      }, true);

      this.handleResize();
    },

    handleResize() {
      this.chartInstance?.resize();
    }
  }
};
</script>

<style scoped>
.chart-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  min-height: 300px; /* Minimum height to ensure visibility */
}

.chart-title {
  text-align: center;
  margin: 2px 0; /* 减小上下边距 */
  font-size: 0.9em; /* 减小字体大小 */
  font-weight: bold;
  color: #333;
  line-height: 1.2; /* 减小行高 */
}

.chart {
  flex-grow: 1;
  width: 100%;
  min-height: 200px; /* Ensure chart has minimum height */
}
</style>
